package com.woniuxy.filter;

import com.woniuxy.dao.UserDao;
import com.woniuxy.entity.User;
import com.woniuxy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    UserDao userDao;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token=request.getHeader("token");
//没有token放行
        if(StringUtils.isEmpty(token)){

            filterChain.doFilter(request, response);

            return;
        }

        //有token验证token是否有效，无效就抛异常 框架底层会处理异常

        if(!JwtUtil.verify(token)){

            throw new  RuntimeException("token已过期");



        }

//token有效就解析token 把用户名拿出来
        String account= JwtUtil.getUname(token);
        User findUser= userDao.selectByAccount(account);
        if(findUser==null){


            throw new RuntimeException("用户不存在");

        }
        //通过token认证以后，告诉框架，现在的请求已经通过认证，后面的Filter不会再拦截这个请求
        //Object principal, 身份信息    完整用户信息
        // Object credentials,凭证
        //Collection<? extends GrantedAuthority> authorities 授权信息
        //一定要使用三个参数的构造器，现在没有管授权，使用null,
        // 三个参数底层才会使用setAuthenticated(true)这个方法，表示通过认证
        Authentication authentication =new UsernamePasswordAuthenticationToken(findUser, null,null );
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
